//
//  homeViewController.m
//  dongfengTest
//
//  Created by wxt on 2021/3/17.
//

#import "HomeViewController.h"
#import "SWQRCode.h"
#import "WKWebViewJavascriptBridge.h"
#import <WebViewJavascriptBridge.h>
#import "ChangeWordViewController.h"
#import "ChangePayWordViewController.h"
#import <WebKit/WebKit.h>
#import "WebViewJavascriptBridge.h"
#import <YYModel.h>
#import "SetUpFaceIDViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "ViewController.h"
#import "LognViewController.h"
//#import <YYCache.h>
@interface HomeViewController ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler,UIScrollViewDelegate>

{
    NSMutableDictionary *handlerDic;
}
@property (nonatomic,strong) WKWebView *webView;
@property(nonatomic, strong) WebViewJavascriptBridge *bridge;

@property (nonatomic ,copy) NSString *fileString;

@end

static NSString *PROTOCOL = @"nstc://";
static NSString *SCHEMA_NATIVE_FETCH_CALL = @"nstc://_native_fetch_call/";
static NSString *SCHEMA_NATIVE_FETCH_CALL_RETURN = @"nstc://_native_fetch_call_return/";

static SignMode mode = SignModeRaw;
static IMHashType hashType = IMHashTypeSM3;
typedef void (^TFMessageCallback)(NSString *responseData);
typedef void (^TFMessageHandler)(NSString *handleName, NSString *callbackData,TFMessageCallback responseCallback);

@implementation HomeViewController

-(void)viewWillAppear:(BOOL)animated {
      self.navigationController.navigationBarHidden = YES;

    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    self.navigationController.navigationBar.shadowImage = [UIImage new];
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
      self.navigationController.navigationBarHidden = YES;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = Wcolor;
    handlerDic = [NSMutableDictionary dictionary];
    
//http://192.168.61.153:8080
//http://192.168.63.240:8080
    
    [self readFile];
    [self creastJsonBridge];

    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.61.200:8080"]]];
    
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"tokenChanger" object:nil];
    
    // Do any additional setup after loading the view.
    

}
-(void)readFile{
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"JSBridge" ofType:@"js"];
    NSData *data = [[NSData alloc] initWithContentsOfFile:path];
    self.fileString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
-(void)creastJsonBridge{

    //获取个人信息
    [self registerHander:@"getUserInfo" handler:^(NSString *handleName,NSString *callbackData, TFMessageCallback responseCallback) {
        NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
        [self loadUserInform:[stand objectForKey:@"userName"] callback:responseCallback];
        
//        NSLog(@"request  handleName === %@",handleName);
    }];
    
    //获取导航条百分比高度
    [self registerHander:@"getStatusBarHeight" handler:^(NSString *handleName, NSString *callbackData,TFMessageCallback responseCallback) {
        CGFloat tabHeight = kStatusBarHeight/kHeight*100;
//        NSLog(@"%.2f",tabHeight);
        NSLog(@"main thread:%@",[NSThread currentThread]);
        responseCallback([NSString stringWithFormat:@"%.2f",tabHeight]);

    }];

    //获取token
    [self registerHander:@"getToken" handler:^(NSString *handleName,NSString *callbackData, TFMessageCallback responseCallback) {

        
        
        NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
        
        NSLog(@"main thread:%@",[NSThread currentThread]);
        
        
        
        responseCallback([stand objectForKey:@"token"]);
        
//        NSLog(@"request  handleName === %@",[stand objectForKey:@"token"]);
    }];

//
    [self registerHander:@"ConsoleLog" handler:^(NSString *handleName, NSString *callbackData, TFMessageCallback responseCallback) {
//        NSLog(@"%@",callbackData);
//        responseCallback(callbackData);
//        NSLog(@"callbackData == %@",callbackData);
    }];
    
    //支付密码
    [self registerHander:@"modifyPayPsd" handler:^(NSString *handleName,NSString *callbackData, TFMessageCallback responseCallback) {
//            NSLog(@"safeRequest  handleName === %@",handleName);

        ChangePayWordViewController * payWordVC = [[ChangePayWordViewController alloc]init];

        payWordVC.modalPresentationStyle = 0;

        [self presentViewController:payWordVC animated:YES completion:nil];

        }];

    //存
    [self registerHander:@"saveString" handler:^(NSString *handleName,NSString *callbackData, TFMessageCallback responseCallback) {
//            NSLog(@"  handleName === %@",callbackData);

        NSDictionary * dic = [TKLTools dictionaryWithJsonString:callbackData];
//        NSLog(@"%@",dic);
        
        NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
        [stand setObject:dic[@"value"] forKey:dic[@"key"]];
        
        responseCallback(@"true");

        }];
    //取
    [self registerHander:@"getString" handler:^(NSString *handleName,NSString *callbackData, TFMessageCallback responseCallback) {
            NSLog(@" handleName === %@",callbackData);
        NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
//        NSString * value = [NSString stringWithFormat:@"%@",[stand objectForKey:callbackData]];
//        [MBProgressHUD showError: value toView:self.view];
        responseCallback(  [stand objectForKey:callbackData]);

        }];

    //登录密码
    [self registerHander:@"modifyLoginPsd" handler:^(NSString *handleName,NSString *callbackData, TFMessageCallback responseCallback) {

//        responseCallback
//        NSLog(@"request  handleName === %@",handleName);
        ChangeWordViewController * chanPassWordVC = [[ChangeWordViewController alloc]init];
        chanPassWordVC.modalPresentationStyle = 0;
        [self presentViewController:chanPassWordVC animated:YES completion:nil];

    }];

    //签名
    [self registerHander:@"detachSign" handler:^(NSString *handleName,NSString *callbackData, TFMessageCallback responseCallback) {
        
        
        [self loadSignSrt:callbackData callback:responseCallback];
//        NSDictionary * dic = [TKLTools dictionaryWithJsonString:callbackData];
        
        
        
        
        
        
        NSLog(@"request  handleName === %@",handleName);
    }];



    //扫码
    [self registerHander:@"scanQRCodeLogin" handler:^(NSString *handleName,NSString *callbackData, TFMessageCallback responseCallback) {
       
        SWQRCodeViewController * codeVC = [[SWQRCodeViewController alloc]init];
        codeVC.modalPresentationStyle = 0;
        [self presentViewController:codeVC animated:YES completion:nil];
        
//        NSLog(@"request  handleName === %@",handleName);
   
    }];
    //生物识别
    [self registerHander:@"biometricIdentify" handler:^(NSString *handleName, NSString *callbackData,TFMessageCallback responseCallback) {
        SetUpFaceIDViewController * faceVC = [[SetUpFaceIDViewController alloc]init];
        faceVC.modalPresentationStyle = 0;
        [self presentViewController:faceVC animated:YES completion:nil];

//        NSLog(@"request  handleName === %@",handleName);
    }];

    //安全退出登录
    [self registerHander:@"safeQuit" handler:^(NSString *handleName, NSString *callbackData, TFMessageCallback responseCallback) {

        LognViewController * viewVC = [[LognViewController alloc]init];
        
        [UIApplication sharedApplication].keyWindow.rootViewController = viewVC;
    }];
    //获取当前平台
    [self registerHander:@"getPlatform" handler:^(NSString *handleName, NSString *callbackData, TFMessageCallback responseCallback) {
        responseCallback(@"IOS");
    }];
}

-(void)registerHander:(NSString *)handerName handler:(TFMessageHandler)handler{
    [handlerDic setValue:handler forKey:handerName];
}

#pragma mark - Https
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
{
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        NSURLCredential *card = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];
        completionHandler(NSURLSessionAuthChallengeUseCredential, card);
    }else {
        completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
    }
    
}

#pragma mark - WKNavigationDelegate

// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    NSLog(@"页面开始加载时调用");
    [MBProgressHUD showActivityMessage:@"加载中"  view:self.view];
    
}

// 当内容开始返回时调用 内容开始到达主帧时被调用（即将完成）
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    NSLog(@"当内容开始返回时调用");
    
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {//这里修改导航栏的标题，动态改变
    [MBProgressHUD hideHUDForView:self.view];
    NSLog(@"页面加载完成之后调用");
    [self.webView evaluateJavaScript:self.fileString completionHandler:nil];

    
}

// 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    //这句是必须加上的，不然会异常
    decisionHandler(WKNavigationResponsePolicyAllow);
}
-(void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    NSLog(@"********%@",error);
    
    
}
// 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    
    self.title = webView.title;
    
    NSLog(@"decidePolicyForNavigationAction = %@",navigationAction.request.URL);
    
    if ([navigationAction.request.URL.absoluteString hasPrefix:PROTOCOL] ) {
       
        if ([navigationAction.request.URL.absoluteString hasPrefix:SCHEMA_NATIVE_FETCH_CALL]) {
            [self.webView evaluateJavaScript:@"JSBridge._native_fetch_call();" completionHandler:nil];
        }else if ([navigationAction.request.URL.absoluteString hasPrefix:SCHEMA_NATIVE_FETCH_CALL_RETURN]){
            
            NSMutableString * str = [NSMutableString stringWithFormat:@"%@",navigationAction.request.URL.absoluteString];
            NSString *callReturn = [str stringByReplacingOccurrencesOfString:SCHEMA_NATIVE_FETCH_CALL_RETURN withString:@""];
            NSArray *arr = [callReturn componentsSeparatedByString:@"/"];
            NSString * handleName = arr.firstObject;
            NSString *callBackID = arr[1];
            NSString *data = arr.lastObject;
            NSString * decodedString = [data stringByRemovingPercentEncoding];
            
//            NSLog(@"%@",decodedString);
            NSLog(@"arr == %@ ",arr.yy_modelDescription);
            NSLog(@"******main thread:%@",[NSThread currentThread]);
            TFMessageHandler hander = [handlerDic valueForKey:handleName];
            if(hander !=nil){
                TFMessageCallback  callback = ^(NSString * callbackData){
                    NSString *returnStr = [NSString stringWithFormat:@"javascript:JSBridge._native_call_return('%@','%@')", callBackID, callbackData];
                [self.webView evaluateJavaScript:returnStr completionHandler:nil];
               };
                hander(handleName,decodedString,callback);
            }
        }
        
        decisionHandler(WKNavigationActionPolicyCancel);
    }else{
        //这句是必须加上的，不然会异常
        decisionHandler(WKNavigationActionPolicyAllow);
    }

}



#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
    
}

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }])];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
    
}

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    [alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alertController.textFields[0].text?:@"");
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
    
}

-(void)loadSignSrt:(NSString *)str callback:(TFMessageCallback)responseCallback{
    NSDictionary * dic = [TKLTools dictionaryWithJsonString:str];
    
    NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
    IMUser * user =[IMUser userWithUserName:[stand objectForKey:@"userName"]];
    
    [user.cert signWithPIN:dic[@"pwd"] Plain:dic[@"plainText"] encoding:NSUTF8StringEncoding hashType:IMHashTypeSM3 mode:mode andCompleteBlock:^(int resultCode, NSString *signResult) {
        {
//                    NSLog(@"%@",resultCode);
            if (resultCode == IM_ER_SUCCESS) {
                if (signResult != nil) {
    
                    responseCallback(signResult);
                    
                }else{
                [MBProgressHUD showError:@"签名失败" toView:self.view];
            }
            }
            
    
    
}
    }];
}

-(void)loadUserInform:(NSString *)userName callback:(TFMessageCallback)responseCallback{

    
    [NetRequestClass TokenAuthNetRequestGETWithRequestURL:kGetUserInfo_Api WithString:userName WithReturnValeuBlock:^(id  _Nonnull returnValue) {
            
        if ([returnValue[@"code"] intValue] == 200) {
            NSDictionary * dataDic = [NSDictionary dictionaryWithDictionary:returnValue[@"data"]];
            
            if ([dataDic isKindOfClass:[NSNull class]] || [dataDic isEqual:[NSNull null]]) {
             
            }else{
                NSLog(@"%@",dataDic.yy_modelToJSONString);
                responseCallback(dataDic.yy_modelToJSONString);
            }
        }
        } WithErrorCodeBlock:^(id  _Nonnull errorCode) {
    
        } WithFailureBlock:^{
           
        }];
   
}
//退出登录
-(void)userLoginOut{
    
    [AFNetworkUtils DELETE:kUser_LoginOut_Api body:nil success:^(NSDictionary * _Nonnull responseObject) {
           NSLog(@"%@",responseObject) ;
        if ([responseObject[@"code"] intValue] == 200) {
            //成功
            UIViewController *rootVC = self.presentingViewController;
            while(rootVC.presentingViewController) {
            rootVC= rootVC.presentingViewController;
            }
            
         [rootVC dismissViewControllerAnimated:YES completion:nil];
            
        }
        
        
        } failure:^(NSString * _Nonnull error) {
            ;
        }];
}

- (WKWebView *)webView {
    if (!_webView) {
        
//        WKWebViewConfiguration *configuration = [WKWebViewConfiguration new];
//        configuration.defaultWebpagePreferences.allowsContentJavaScript = YES;
        
        WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, kStatusBarHeight, CGRectGetWidth(self.view.frame), kHeight-HOME_INDICATOR_HEIGHT-kStatusBarHeight)];
        webView.navigationDelegate = self;
        webView.UIDelegate = self;
        webView.scrollView.delegate = self;
        
        
        webView.scrollView.bounces = NO;
        if (@available(iOS 11.0, *)) {
            webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            UIEdgeInsets inset = UIEdgeInsetsMake(0, 0, 0, 0);
            webView.scrollView.contentInset = inset;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        };
        

        _webView = webView;
        
        [self.view addSubview:self.webView];

    }
    
    return _webView;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
